package com.asseco.mio.codex.controllers;

import com.asseco.mio.codex.Country;
import com.asseco.mio.codex.Municipality;
import com.asseco.mio.codex.Nationality;
import com.asseco.mio.codex.EduLvl;
import com.asseco.mio.codex.GeoArea;
import com.asseco.mio.BasicInfo;
import com.asseco.mio.codex.BasicInfoForm;
import com.asseco.mio.codex.DeleteReason;
import com.asseco.mio.core.model.AuditLog;
import com.asseco.mio.core.webapp.controller.*;
import com.asseco.mio.validators.EMBGValidator;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.apache.commons.lang.StringUtils;
import org.appfuse.service.GenericManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.validation.ObjectError;
import org.springframework.validation.Validator;

@Controller
@RequestMapping("/basicinfoform*")
public class BasicInfoFormController extends BaseFormController {

    private GenericManager<GeoArea, String> geoAreaManager = null;
    private GenericManager<Country, String> countryManager = null;
    private GenericManager<Municipality, String> municipalityManager = null;
    private GenericManager<Nationality, String> nationalityManager = null;
    private GenericManager<BasicInfo, String> basicInfoManager = null;
    private GenericManager<EduLvl, String> eduLvlManager = null;
    private GenericManager<AuditLog, String> auditLoggerManager = null;
    private GenericManager<DeleteReason, String> deleteReasonManager = null;
    
    
    @Autowired(required = false)
    Validator validator;

    @Autowired
    public void setGeoAreaManager(@Qualifier("geoAreaManager") GenericManager<GeoArea, String> geoAreaManager) {
        this.geoAreaManager = geoAreaManager;
    }

    @Autowired
    public void setCountryManager(@Qualifier("countryManager") GenericManager<Country, String> countryManager) {
        this.countryManager = countryManager;
    }

    @Autowired
    public void setMunicipalityManager(@Qualifier("municipalityManager") GenericManager<Municipality, String> municipalityManager) {
        this.municipalityManager = municipalityManager;
    }

    @Autowired
    public void setNationalityManager(@Qualifier("nationalityManager") GenericManager<Nationality, String> nationalityManager) {
        this.nationalityManager = nationalityManager;
    }

    @Autowired
    public void setBasicInfoManager(@Qualifier("basicInfoManager") GenericManager<BasicInfo, String> basicInfoManager) {
        this.basicInfoManager = basicInfoManager;
    }

    @Autowired
    public void setEduLvlManager(@Qualifier("eduLvlManager") GenericManager<EduLvl, String> eduLvlManager) {
        this.eduLvlManager = eduLvlManager;
    }
    @Autowired
    public void setAuditLoggerManager(GenericManager<AuditLog, String> auditLoggerManager) {
        this.auditLoggerManager = auditLoggerManager;
    }

    @Autowired
    public void setDeleteReasonManager(GenericManager<DeleteReason, String> deleteReasonManager) {
        this.deleteReasonManager = deleteReasonManager;
    }

    public BasicInfoFormController() {
        setCancelView("redirect:basicinfo");
        setSuccessView("redirect:basicinfo");
    }

    @ModelAttribute
    public BasicInfoForm basicInfoForm() {
        BasicInfoForm x = new BasicInfoForm(getAllActiveGeoArea(this.geoAreaManager.getAll()), getAllActiveCountry(this.countryManager.getAll()), getAllActiveMunicipality(this.municipalityManager.getAll()), getAllActiveNationality(this.nationalityManager.getAll()), getAllActiveEduLvl(this.eduLvlManager.getAll()), this.deleteReasonManager.getAll());
        return x;
    }

    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    protected BasicInfoForm showForm(HttpServletRequest request)
            throws Exception {

        String id = request.getParameter("id");
        if (!StringUtils.isBlank(id)) {
            BasicInfoForm x = this.basicInfoForm();
            x.setBasicInfo(basicInfoManager.get(id));
            auditLoggerManager.save(new AuditLog(request.getRemoteUser(), "basicinfoform", "basicInfo.show", x.getBasicInfo().getLastName() + " " + x.getBasicInfo().getFirstName(),
                    "test",request.getRemoteHost() ,new Date()));

            return x;
        }
       
        BasicInfoForm x = new BasicInfoForm(getAllActiveGeoArea(this.geoAreaManager.getAll()), getAllActiveCountry(this.countryManager.getAll()), getAllActiveMunicipality(this.municipalityManager.getAll()), getAllActiveNationality(this.nationalityManager.getAll()), getAllActiveEduLvl(this.eduLvlManager.getAll()));
        Country count = countryManager.get("8a808a9c3003754e0130037c770b00a7");
        x.setBasicInfo(new BasicInfo());
        x.getBasicInfo().setBirthCountry(count);
        return x;
    }

    @RequestMapping(method = RequestMethod.POST)
    public String onSubmit(BasicInfoForm basicInfoForm, BindingResult errors, HttpServletRequest request,
            HttpServletResponse response)
            throws Exception {
        if (request.getParameter("cancel") != null) {
            return getCancelView();
        }

//            String userName =  request.getRemoteUser();
//           User user = UserSearch.getUserByUserName(userName);
        //  Set testSet = user.getRoles();

        //  System.out.println("Rolji = "+testSet.toString());

        if (validator != null) { // validator is null during testing
            //  validator.validate(basicInfoForm, errors);

            if (errors.hasErrors() && request.getParameter("delete") == null) { // don't validate when deleting
                return "basicinfoform";
            }
        }

        log.debug("entering 'onSubmit' method...");



        boolean isNew = (basicInfoForm.getBasicInfo().getId().equals(""));
        String success = getSuccessView();
        Locale locale = request.getLocale();


         if (!basicInfoForm.getSavedReason().getId().equals("")) {
            try{
                basicInfoManager.remove(basicInfoForm.getBasicInfo().getId());
                saveMessage(request, getText("basicInfo.deleted", locale));
                 String deleteReasonString = deleteReasonManager.get(basicInfoForm.getSavedReason().getId()).toString();
                 String tempString = basicInfoForm.getBasicInfo().toString();
                 String remoteUser = request.getRemoteUser();
                 String remoteHost = request.getRemoteHost();
                 auditLoggerManager.save(new AuditLog(remoteUser, "basicinfoform","basicInfo.delete", tempString, deleteReasonString, remoteHost, new Date()));
                
            }
            catch (Exception e){
                saveMessage(request, getText("basicInfo.Nemoze_da_se_izbrise_zatoa_sto_veke_ima_vneseno_prijavi_i_odjavi", locale));
                success = "redirect:basicinfoform?id=" + basicInfoForm.getBasicInfo().getId();
            }
        } else {
            if(basicInfoForm.getBasicInfo().getBirthCountry().getId().equals("8a808a9c3003754e0130037c770b00a7")){
                String socSocNumber = basicInfoForm.getBasicInfo().getSocScrNo();
                EMBGValidator v = new EMBGValidator();
                int isValid = v.checkEMBG(socSocNumber);
                if (isValid==0){
                    saveMessage(request, getText("basicInfo.socScrNumberNotValid", locale));
                    return "basicinfoform";
                }
            }

            

            basicInfoManager.save(basicInfoForm.getBasicInfo());
            String key = (isNew) ? "basicInfo.added" : "basicInfo.updated";
            saveMessage(request, getText(key, locale));
            AuditLog al = new AuditLog(request.getRemoteUser(), "basicinfoform", key, basicInfoForm.getBasicInfo().getLastName() + " " + basicInfoForm.getBasicInfo().getFirstName(),
                    request.getQueryString(),request.getRemoteHost(), new Date());
            
            auditLoggerManager.save(al);
                

            if (!isNew) {
                success = "redirect:basicinfoform?id=" + basicInfoForm.getBasicInfo().getId();
                auditLoggerManager.save(new AuditLog(request.getRemoteUser(), "basicinfoform", "basicInfo.cancel", basicInfoForm.getBasicInfo().getLastName() + " " + basicInfoForm.getBasicInfo().getFirstName(),
                        request.getQueryString(),request.getRemoteHost() ,new Date()));
            }
        }
        return success;
    }

   

    @Override
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
        super.initBinder(request, binder);
        SimpleDateFormat dateFormat =
                new SimpleDateFormat(getText("dd/MM/yyyy", request.getLocale()));
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, null, new CustomDateEditor(dateFormat, true));
    }

    public List getAllActiveGeoArea(List<GeoArea> list) {

        List result = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            GeoArea ga = list.get(i);
            if (ga.getStatus() == true) {
                result.add(ga);
            }

        }

        return result;
    }

    public List getAllActiveCountry(List<Country> list) {

        List result = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            Country ga = list.get(i);
            if (ga.getStatus() == true) {
                result.add(ga);
            }

        }

        return result;
    }

    public List getAllActiveNationality(List<Nationality> list) {

        List result = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            Nationality ga = list.get(i);
            if (ga.getStatus() == true) {
                result.add(ga);
            }

        }

        return result;
    }

    public List getAllActiveMunicipality(List<Municipality> list) {

        List result = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            Municipality ga = list.get(i);
            if (ga.getStatus() == true) {
                result.add(ga);
            }

        }

        return result;
    }

    public List getAllActiveEduLvl(List<EduLvl> list) {

        List result = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            EduLvl ga = list.get(i);
            if (ga.getStatus() == true) {
                result.add(ga);
            }

        }

        return result;
    }
}
